package com.xd.Controller.admin.XTGLY;
import com.google.gson.Gson;
import com.xd.Dto.AddProductDto;
import com.xd.Dto.IFSelectProductDto;
import com.xd.Dto.ProductPageQueryDTO;
import com.xd.Entity.EntityBrand;
import com.xd.Entity.EntityCatergory;
import com.xd.Entity.EntityUnit;
import com.xd.Entity.ProductEntity;
import com.xd.Result.CommonResult;
import com.xd.Result.PageResult;
import com.xd.Util.JwtUtil;
import com.github.pagehelper.PageInfo;
import com.xd.Util.RedisUtils;
import com.xd.pojo.User;
import com.xd.service.admin.XTGLY.UnitlikeService;
import com.xd.service.admin.XTGLY.impl.*;
import com.xd.vo.ProductQueryParamVo;
import com.xd.vo.updateStatusVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.xd.erroCode.Errcode;
import com.xd.vo.productVo;
import pojo.XTGLY.Catergory;
import pojo.XTGLY.UnitParam;
import pojo.XTGLY.brandParam;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;
import java.util.Set;
@RestController
@RequestMapping("/admin")
public class adminLogin {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    AdminGetProductInforImpl adminGetProductInfor;
    @Autowired
    AdminLoginServiceImpl adminLoginService;
    @Autowired
    updateProductServiceImpl updateProductService;
    @Autowired
    AddProductServiceImpl addProductService;
    @Autowired
    UnitServiceImpl unitProductService;
    @Autowired
    CatergoryProductServiceImpl catergoryProductService;
    @Autowired
    BrandProductServiceImpl BrandProductService;
    @Autowired
    deleteProductServiceImpl deleteProductService;
    @Autowired
    LikeServiceImpl likeService;
    @Autowired
    BrandlikeServiceImpl brandlikeServiceImpl;
    @Autowired
    CatergorylikeServiceImpl catergorylikeService;
    @Autowired
    UnitlikeService unitlikeService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    UpdateProductStatusServiceImpl updateProductStatusService;

    /**
     * 管理后台登录接口
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public CommonResult<String> getUser(@RequestBody User user) {
        Boolean flag = adminLoginService.getUser(user);
        if (flag) {
            return CommonResult.Success(jwtUtil.generateToken(user.getUserName()));
        } else {
            return CommonResult.error(Errcode.LOGIN_ERRODE, null);
        }
    }

    /**
     * 修该商品信息
     *
     * @return/
     */
    @PutMapping("/UpdateProduct")
    public CommonResult updateProduct(@RequestBody productVo productVo) {
        productVo.setUpdateTime(LocalDateTime.now());
        CommonResult commonResult = updateProductService.updateProduct(productVo);
        Set<String> allKeys = redisTemplate.keys("product_cache:*");
        if (allKeys!= null &&!allKeys.isEmpty()) {
            redisTemplate.delete(allKeys);
        }
        return commonResult;
    }

    /**
     * 分页查询商品信息
     *
     * @return
     */
    @GetMapping("/getProduct")
    public CommonResult<PageResult> getProduct(ProductPageQueryDTO productPageQueryDTO) {
        // 定义缓存前缀
        String cachePrefix = "product_cache:";
        // 获取分页参数并拼接到缓存 key 中
        String pageParam = productPageQueryDTO.getPage() + "_" + productPageQueryDTO.getPageSize();
        String key = cachePrefix + pageParam;

        //PageResult pageResult = (PageResult) redisTemplate.opsForValue().get(key);
        Object result = redisUtils.get(key);
        String json = new Gson().toJson(result);
        PageResult pageResult = new Gson().fromJson(json, PageResult.class);
        if (pageResult!= null) {
            return CommonResult.Success(pageResult);
        }

        pageResult = adminGetProductInfor.getProduct(productPageQueryDTO);
        redisUtils.set(key, pageResult);
        return CommonResult.Success(pageResult);
    }

    /**
     * 分页查询商品单位
     */
    @GetMapping("/getUnit")
    public CommonResult<PageResult> getUnit(ProductPageQueryDTO pageQueryDTO) {
        String cachePrefix = "UnitCatch:";
        // 获取分页参数并拼接到缓存 key 中
        String pageParam =  pageQueryDTO.getPage() + "_" + pageQueryDTO.getPageSize();
        String key = cachePrefix + pageParam;
        Object result = redisUtils.get(key);
        String json = new Gson().toJson(result);
        PageResult pageResult = new Gson().fromJson(json, PageResult.class);
        if( pageResult!=null){
            return CommonResult.Success(pageResult);
        }

         pageResult = unitProductService.getUnit(pageQueryDTO);
        redisUtils.set(key, pageResult);

        return CommonResult.Success(pageResult);

    }


    /**
     * 分页查询商品分类
     */
    @GetMapping("/getCatergory")
    public CommonResult<PageResult> getCatergory(ProductPageQueryDTO pageQueryDTO) {
        String cachePrefix = "CategoryCatch:";
        // 获取分页参数并拼接到缓存 key 中
        String pageParam =  pageQueryDTO.getPage() + "_" + pageQueryDTO.getPageSize();
        String key = cachePrefix + pageParam;
        Object result = redisUtils.get(key);
        String json = new Gson().toJson(result);
        PageResult pageResult = new Gson().fromJson(json, PageResult.class);
        if (pageResult!=null){
            return CommonResult.Success(pageResult);
        }
         pageResult = catergoryProductService.getCatergory(pageQueryDTO);
        redisUtils.set(key, pageResult);
        return CommonResult.Success(pageResult);

    }

    /**
     * 分页查询商品品牌
     */
    @GetMapping("/getBrand")
    public CommonResult<PageResult> getBrand(@RequestBody ProductPageQueryDTO pageQueryDTO) {
        String cachePrefix = "BrandCatch:";
        // 获取分页参数并拼接到缓存 key 中
        String pageParam =  pageQueryDTO.getPage() + "_" + pageQueryDTO.getPageSize();
        String key = cachePrefix + pageParam;
        Object result = redisUtils.get(key);
        String json = new Gson().toJson(result);
        PageResult pageResult = new Gson().fromJson(json, PageResult.class);
        if (pageResult!=null){
            return CommonResult.Success(pageResult);
        }
        pageResult = BrandProductService.getBrand(pageQueryDTO);
        redisUtils.set(key, pageResult);
        return CommonResult.Success(pageResult);

    }

    /**
     * 新增商品信息
     */
    @PostMapping("/addProduct")
    public CommonResult addProduct(@RequestBody AddProductDto addProductDto) {

      productVo productVo = new productVo();
        BeanUtils.copyProperties(addProductDto,productVo);
        long timestamp = System.currentTimeMillis();

        LocalDateTime createTime = LocalDateTime.now();

        String ProductXu=timestamp+addProductDto.getName();
                 productVo.setStatus('1');
                 productVo.setProductXu(ProductXu);
                 productVo.setCreateTime(createTime);
        CommonResult commonResult = addProductService.addProduct(productVo);

        Set<String> allKeys = redisTemplate.keys("product_cache*");
        if (allKeys!= null &&!allKeys.isEmpty()) {
            redisTemplate.delete(allKeys);
        }
        return commonResult;
    }

//    /**
//     * 删除商品信息
//     */
//    @DeleteMapping("/deleteProduct")
//    public CommonResult deleteProduct(Integer ProductId) {
//        deleteProductService.deleteProductServiceById(ProductId);
//        return CommonResult.Success();
//    }

    /**
     * 商品管理：根据某个字段查询商品信息
     */
    @GetMapping("/query/product")
    public CommonResult<PageInfo<ProductEntity>> queryProducts(ProductQueryParamVo productQueryParamVo) {
        if (productQueryParamVo.getProductBrand()!=null&&productQueryParamVo.getProductBrand().equals("")){
            productQueryParamVo.setProductBrand(null);
        }
        if (productQueryParamVo.getProductCatergory()!=null&&productQueryParamVo.getProductCatergory().equals("")){
            productQueryParamVo.setProductCatergory(null);
        }
        if (productQueryParamVo.getName()!=null&&productQueryParamVo.getName().equals("")){
            productQueryParamVo.setName(null);
        }
        if (productQueryParamVo.getStatus()!=null&&productQueryParamVo.getStatus().equals("")){
            productQueryParamVo.setStatus(null);
        }
        IFSelectProductDto ifSelectProductDto = new IFSelectProductDto();
        BeanUtils.copyProperties(productQueryParamVo, ifSelectProductDto);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy - MM - dd HH:mm:ss", Locale.US);

        // 处理 createTimeStart
        String createTimeStartStr = productQueryParamVo.getCreateTimeStart();
        if (createTimeStartStr != null && !createTimeStartStr.trim().isEmpty()&& !(createTimeStartStr.equals("0"))) {
            try {
                LocalDateTime createTimeStart = LocalDateTime.parse(createTimeStartStr, formatter);
                ifSelectProductDto.setCreateTimeStart(createTimeStart);
            } catch (DateTimeParseException e) {
                e.printStackTrace();
                // 可以根据需求返回错误信息或者进行其他处理
                return CommonResult.error("createTimeStart 时间格式解析错误");
            }
        }

        // 处理 createTimeEnd
        String createTimeEndStr = productQueryParamVo.getCreateTimeEnd();
        if (createTimeEndStr != null && !createTimeEndStr.trim().isEmpty()&&!(createTimeEndStr.equals("0"))) {
            try {
                LocalDateTime createTimeEnd = LocalDateTime.parse(createTimeEndStr, formatter);
                ifSelectProductDto.setCreateTimeEnd(createTimeEnd);
            } catch (DateTimeParseException e) {
                e.printStackTrace();
                return CommonResult.error("createTimeEnd 时间格式解析错误");
            }
        }

        // 处理 updateTimeStart
        String updateTimeStartStr = productQueryParamVo.getUpdateTimeStart();
        if (updateTimeStartStr != null && !updateTimeStartStr.trim().isEmpty()&&!(updateTimeStartStr.equals("0"))) {
            try {
                LocalDateTime updateTimeStart = LocalDateTime.parse(updateTimeStartStr, formatter);
                ifSelectProductDto.setUpdateTimeStart(updateTimeStart);
            } catch (DateTimeParseException e) {
                e.printStackTrace();
                return CommonResult.error("updateTimeStart 时间格式解析错误");
            }
        }

        // 处理 updateTimeEnd
        String updateTimeEndStr = productQueryParamVo.getUpdateTimeEnd();
        if (updateTimeEndStr != null && !updateTimeEndStr.trim().isEmpty()&&!(updateTimeEndStr.equals("0"))) {
            try {
                LocalDateTime updateTimeEnd = LocalDateTime.parse(updateTimeEndStr, formatter);
                ifSelectProductDto.setUpdateTimeEnd(updateTimeEnd);
            } catch (DateTimeParseException e) {
                e.printStackTrace();
                return CommonResult.error("updateTimeEnd 时间格式解析错误");
            }
        }

        PageInfo<ProductEntity> productPageInfo = likeService.getproductLikeService(ifSelectProductDto);
        return CommonResult.Success(productPageInfo);
    }

    /**
     * 商品品牌：根据某个字段查询
     */
    @PostMapping("/query/brand")
    public CommonResult<PageInfo<EntityBrand>> queryqueryProductBrand(@RequestBody brandParam brandParam) {
        PageInfo<EntityBrand> productPageBrand = brandlikeServiceImpl.getBrand(brandParam);
        return CommonResult.Success(productPageBrand);

    }

    /**
     * 商品分类：根据某个字段查询
     */
    @PostMapping("/query/Catergory")
    public CommonResult<PageInfo<EntityCatergory>> queryqueryProductCatergory(@RequestBody Catergory Catergory) {
        PageInfo<EntityCatergory> productPageBrand = catergorylikeService.getCatergory(Catergory);
        return CommonResult.Success(productPageBrand);
    }

    /**
     * 商品单位：根据某个字段查询
     */
    @PostMapping("/query/Unit")
    public CommonResult<PageInfo<EntityUnit>> queryqueryProductUnit(@RequestBody UnitParam unitParam) {
        PageInfo<EntityUnit> productPageBrand = unitlikeService.getUnit(unitParam);
        return CommonResult.Success(productPageBrand);
    }
    /**
     * 更改商品状态
     */
    @PostMapping("updateProductStatus")
    public CommonResult<LocalDateTime> updateProductStatus(@RequestBody updateStatusVo updateStatusVo){
        LocalDateTime updateTime = LocalDateTime.now();
        updateProductStatusService.update(updateStatusVo);
        Set<String> allKeys = redisTemplate.keys("product_cache:*");
        if (allKeys!= null &&!allKeys.isEmpty()) {
            redisTemplate.delete(allKeys);
        }
        return CommonResult.Success(updateTime);
    }
}









